package com.example.kugou.common.email;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public abstract class EmailUtils {

    private static final EamilCode eamilCode = new EamilCode();

    public EamilCode getEamilCode() {
        return eamilCode;
    }

    public static String achieveCode(){
        String[] beforeShuffle = new String[]{"0","1","2","3","4","5","6","7","8","9","q","w","e","r","t",
        "y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n",
        "m","Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K",
        "L","Z","X","C","V","B","N","M"};
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb  = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(3, 9);
        return result;
    }
    public static String sendEamilCode(String email) {
        HtmlEmail send = new HtmlEmail();
        String resultCode = achieveCode();
        try {
            send.setHostName("smtp.qq.com");//发送服务
            send.setSmtpPort(465);//发送端口号
            send.setSSLOnConnect(true);//开启 SSL 加密
            send.setCharset("utf-8");
            send.addTo(email);
            send.setFrom("1678576197@qq.com");
            send.setAuthentication("1678576197@qq.com", "kdpoxkpwmidyjahj");
            send.setSubject("爱奇艺官方");
            send.setMsg("您正在注册爱奇艺账号，你的验证码是：" + resultCode + "哈哈哈");
            send.send(); //发送
            eamilCode.setResultCode(resultCode);
            eamilCode.setFailure(System.currentTimeMillis());
        } catch (EmailException e) {
            e.printStackTrace();
        }
        return resultCode;//返回验证码
    }

    public static Boolean codeIsRight(String code){
        long now = System.currentTimeMillis();
        return code == eamilCode.getResultCode() && now < eamilCode.getFailure();
    }
}
